package com.yiyi.credit.manage.abutment.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yiyi.credit.manage.abutment.common.constant.ParamConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class SignatureUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(SignatureUtils.class);

    public static boolean checkSign(String jsonStr,String privateKey) {

        JSONObject obj =  JSONObject.parseObject(jsonStr);
        String signSrc = genSignData(obj);
        String sign= (String) obj.get("sign");
        return checkSignUpper(sign,signSrc,privateKey);
    }

    /**
     * 生成待签名串
     *
     * @param
     * @return
     */
    public static String genSignData(JSONObject jsonObject) {
        StringBuffer content = new StringBuffer();

        // 按照key做首字母升序排列
        List<String> keys = new ArrayList<String>(jsonObject.keySet());
        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            // sign 和ip_client 不参与签名
            if ("sign".equals(key)) {
                continue;
            }
            String value = (String) jsonObject.getString(key);
            // 空串不参与签名
            if (StringUtils.isEmpty(value)) {
                continue;
            }
            content.append((i == 0 ? "" : "&") + key + "=" + value);

        }
        String signSrc = content.toString();
        if (signSrc.startsWith("&")) {
            signSrc = signSrc.replaceFirst("&", "");
        }
        return signSrc;
    }

    public static String sign(String signSrc, String key) {
        LOGGER.info("最终待签串:{}",signSrc +"&key="+key);
        return SecurityUtils.md5(signSrc +"&key="+key).toUpperCase();
    }

    public static boolean checkSignUpper(String sign, String signSrc,String key) {
        LOGGER.info("最终检验待签串:{}",signSrc +"&key="+key);
        String newSign = SecurityUtils.md5(signSrc +"&key="+key ).toUpperCase();
        LOGGER.info("最终newSign:{} 判断{}",newSign,sign.equals(newSign));
        return sign.equals(newSign);
    }
}
